﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AI3SaveEditor.AI3Files;

namespace AI3SaveEditor
{
    public partial class ClothesNamesEditor : Form
    {
        IEnumerable<ClothesFile> clothesFiles;
        ListView.ListViewItemCollection allItems;
        private ClothesNamesEditor() {
            InitializeComponent();
        }

        public ClothesNamesEditor(IEnumerable<ClothesFile> clothesFiles, ListView.ListViewItemCollection allItems)
            : this() {
            this.clothesFiles = clothesFiles;
            this.allItems = allItems;
            txtNumber.Maximum = 999 - CollectionHelper.Count(clothesFiles);
        }

        private void btnOK_Click(object sender, EventArgs e) {
            string template = cboPrefix.Text + "{0}";

            int i = 0;

            foreach (var each in clothesFiles) {
                each.Name = string.Format(template, GetNextNumberString(i + (int)txtNumber.Value));
                each.Save();
                i++;
            }
        }

        private string GetNextNumberString(int number) {
            string result = number.ToString();
            while (result.Length < 3) {
                result = "0" + result;
            }
            return result;
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e) {
            if (cboPrefix.SelectedIndex > -1) {
                int max = 0;
                foreach (ListViewItem item in allItems) {
                    if (item.Text.StartsWith(cboPrefix.Text)) {
                        int value = 0;
                        if (int.TryParse(item.Text.Replace(cboPrefix.Text, string.Empty), out value)) {
                            if (value > max)
                                max = value;
                        }
                    }
                }
                txtNumber.Value = max + 1;
            }
        }
    }
}
